﻿using System;
using System.Linq;
using System.Web.Mvc;
using WebSite.Models;
using Xwltz.Framework.Helper;

namespace WebSite.Class
{
    public class LogAttribute : ActionFilterAttribute
    {

        /// <summary>
        /// 执行后
        /// </summary>
        /// <param name="filterContext"></param>
        public override void OnActionExecuted(ActionExecutedContext filterContext)
        {
            var session = filterContext.HttpContext.Session["AccountModel"];
            var model = new AccountLog();

            var query = filterContext.ActionDescriptor.GetCustomAttributes(typeof(QueryLogAttribute), true);
            var save = filterContext.ActionDescriptor.GetCustomAttributes(typeof(SaveLogAttribute), true);
            var delete = filterContext.ActionDescriptor.GetCustomAttributes(typeof(DeleteLogAttribute), true);

            if (session != null)
            {
                var account = filterContext.HttpContext.Session["AccountModel"].ToString().ToObject<Account>();
                model.UserId = account.Id;
                model.UserName = account.Name;
            }
            else
            {
                model.UserId = 0;
                model.UserName = "";
            }

            if (query.Any()) model.Type = (int)LogTypeEnum.Query;
            if (save.Any()) model.Type = (int)LogTypeEnum.Save;
            if (delete.Any()) model.Type = (int)LogTypeEnum.Delete;

            model.Path = filterContext.HttpContext.Request.RawUrl;
            model.Method = filterContext.HttpContext.Request.HttpMethod;
            model.Host = ClientHelper.GetIpAddress;
            model.UserAgent = ClientHelper.GetUserAgent();
            model.Area = HostHelper.GetHostInfo(model.Host);
            model.Request = filterContext.HttpContext.Request.QueryString.ToString();
            model.Response = filterContext.HttpContext.Response.StatusDescription;
            model.AddTime = DateTime.Now;
            model.Description = "执行成功";

            new DbContext().GetInstance().Insertable(model).ExecuteCommand();
            base.OnActionExecuted(filterContext);
        }
    }

    public class QueryLogAttribute : Attribute
    {
    }

    public class SaveLogAttribute : Attribute
    {
    }

    public class DeleteLogAttribute : Attribute
    {
    }
}